import Reflux from 'reflux';
import PageConst from './PageConst';
import Actions from './Actions';
import update from 'react-addons-update';
import nattyStorage from 'natty-storage';
import DB from '../../../app/db';

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    city: "",
    ...PageConst,
    markers: [],
    districtAvg: [],
    mapInstance: null,
    todayTime: "",
    tab: 1
  },

  onLoadData: function (city) {
    let that = this;
    DB.WechatAPI.querypmapByCity({
      city: city
    }).then(
      function (content) {
        console.info(content)
        that.data = update(that.data, {
          city: {
            $set: city,
          },
          markers: {
            $set: content.pmap
          }
        });

        that.updateComponent();
        that.onLoadDistrictData();
      },
      function (error) {
        console.log(error);
      }
    );
  },

  onSetMapInstance: function (mapInstance) {
    this.data.mapInstance = update(this.data.mapInstance, {$set: mapInstance});
  },

  onLoadDistrictData: function () {
    let that = this;
    DB.WechatAPI.queryAvgByDistrict({
      city: that.data.city
    }).then(
      function (content) {
        console.info(content)
        that.data.districtAvg = update(that.data.districtAvg, {$set: content.districtAvg});
        that.data.todayTime = update(that.data.todayTime, {$set: content.todayTime});
        let mapInstance = that.data.mapInstance;
        mapInstance.setCity(that.data.city);
        that.updateComponent();
      },
      function (error) {
        console.log(error);
      }
    );
  },

  onSetPmTab: function () {
    this.data.tab = update(this.data.tab, {$set: 1});
    this.updateComponent();
  },

  onSetZaoyinTab: function () {
    this.data.tab = update(this.data.tab, {$set: 2});
    this.updateComponent();
  },

  onFetch: function (params, cb) {
    let t = this;
    t.updateComponent();
    cb && cb(t.data);
  },

  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  }
});
